package ServerInfoUtils

import (
	"os"
	"errors"
	"net"
	"strings"
)

func GetHostName()(string,error){
	return os.Hostname()
}

func GetIP()(string,error){
	//默认采用HOSTNAME获取IP
	var ip,err = GetIPByHostName()
	if(err==nil){
		return ip,err
	}
	//其次采用internatename = eth0获取IP
	ip,err = GetIPByInternetName("eth0")
	if(err==nil){
		return ip,err
	}
	return "",errors.New("根据HOSTNAME和网卡eth0获取IP地址失败")
}

func GetIPByInternetName(internetname string)(string,error){
	interfaceinfo, err := net.InterfaceByName(internetname)
	if err != nil{
		return "",err
	}
	var addrs,_ = interfaceinfo.Addrs()
	for _,addr := range addrs {
		ipnet, ok := addr.(*net.IPNet)
		var ip = ipnet.IP.String()
		if ok && strings.Index(ip,":")<0{
			return ip,nil
		}
	}
	return "",errors.New("未找到对应的网卡")
}

func GetIPByHostName()(string,error){
	hostname,err1 := GetHostName()
	if(err1!=nil){
		return "",err1
	}
	IPS,err2 := net.LookupIP(hostname)
	if(err2!=nil){
		return "",err2
	}
	for _,IP := range IPS {
		var ip = IP.String()
		if strings.Index(ip,":")<0{
			return ip,nil
		}
	}
	return "",nil
}

func GetPid()(int){
	return os.Getpid()
}
